package com.gitee.magic.jdbc.spring.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import com.gitee.magic.jdbc.persistence.EntityFactory;
import com.gitee.magic.jdbc.persistence.EntityFactoryAware;

/**
 * @author start
 */
public class EntityFactoryContextAwareProcessor implements BeanPostProcessor {
	
//	private final ConfigurableListableBeanFactory beanFactory;
	private final EntityFactory factory;

	/**
	 * Create a new ApplicationContextAwareProcessor for the given context.
	 */
	public EntityFactoryContextAwareProcessor(ConfigurableListableBeanFactory beanFactory,EntityFactory factory) {
//		this.beanFactory=beanFactory;
		this.factory = factory;
	}


	@Override
	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {

//		AccessControlContext acc = null;
//
//		if (System.getSecurityManager() != null &&
//				(bean instanceof EntityFactoryAware)) {
//			acc = this.beanFactory.getAccessControlContext();
//		}
//
//		if (acc != null) {
//			AccessController.doPrivileged(new PrivilegedAction<Object>() {
//				@Override
//				public Object run() {
//					invokeAwareInterfaces(bean);
//					return null;
//				}
//			}, acc);
//		}
//		else {
			invokeAwareInterfaces(bean);
//		}
		
		return bean;
	}

	private void invokeAwareInterfaces(Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof EntityFactoryAware) {
				((EntityFactoryAware) bean).setEntityFactory(this.factory);
			}
		}
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		return bean;
	}
	
}
